from machine import RTC

def days_in_month(year, month):
    # 返回某年某月的天数（修正闰年）
    if month == 2:
        return 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 28
    return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month-1]

def datetime_to_seconds(dt):
    year, month, day, _, hour, minute, second, _ = dt
    total_days = 0
    for y in range(2000, year):
        total_days += 366 if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0) else 365
    for m in range(1, month):
        total_days += days_in_month(year, m)
    total_days += day - 1
    return total_days * 86400 + hour * 3600 + minute * 60 + second

class datetime(object):
    rtc = None
    def __init__(self,rtc=None):
        if rtc is not None:
            self.rtc = rtc
        else:
            self.rtc = RTC()
            
    def get_datetime(self):
        return self.rtc.datetime()

    def format_datetime(self):
        t = self.get_datetime()
        if t == "":
            return ""
        else:
            return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(t[0],t[1],t[2],t[4],t[5],t[6])

    def format_date(self):
        t = self.get_datetime()
        if t == "":
            return ""
        else:
            return "{:04d}-{:02d}-{:02d}".format(t[0],t[1],t[2])

    def format_time(self):
        t = self.get_datetime()
        if t == "":
            return ""
        else:
            return "{:02d}:{:02d}:{:02d}".format(t[4],t[5],t[6])
    